package ase.eleitweg.server;

import java.rmi.RemoteException;
import java.rmi.server.ExportException;
import java.rmi.server.UnicastRemoteObject;

import com.google.inject.Inject;

import ase.eleitweg.common.*;
import ase.eleitweg.server.db.ELeitwegDAO;


public class AdminLoginController extends
		AbstractLoginController<ServerAdminHandle> implements
		AdminLoginInterface {
	
	
	private static AdminLoginInterface instance = null;
		
	private volatile AdminHandle handle = null;

	private AdminLoginController() {
		Thread pinger = new Thread(new Pinger());
		pinger.start();
	}
	
	@Inject
	ServerAdminHandle sah;

	public ServerAdminHandle getSC() throws RemoteException {
		// return new ServerAdminController();
		try {
			return (ServerAdminHandle) UnicastRemoteObject.exportObject(sah, 0);
		} catch (ExportException e) {
			// the object already exported
			return sah;
		}
	}

	@Override
	protected boolean isAuthorised(String username, String md5passwd, User u) {
		if (username.equalsIgnoreCase(u.getUsername())
				&& md5passwd.equals(u.getPasswdhash()) && u.isAdmin())
			return true;
		return false;
	}
	
	public boolean checkUnique(AdminHandle ah) {
		if(handle == null) {
			handle = ah;
			return true;
		} else {
			return false;
		}
	}
	
	private class Pinger implements Runnable {
		public void run() {
			while(true) {
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					//nothing to do
				}
				if(handle == null) {
					continue;
				}
				try {
					handle.ping();
				} catch (RemoteException e) {
					handle = null;
				}
			}
		}
	}


}
